//
//  TXToastCenter.m
//  TXKit
//
//  Created by YM on 15/11/24.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "TXToastCenter.h"

#define ALERT_VIEW_HEIGHT 200


#pragma mark - TXAlertView

@interface TXToastView : UIView {
    CGRect _messageRect;
}
@property (nonatomic,strong) UIImage *image;
@property (nonatomic,copy) NSString *messageText;

@end

@implementation TXToastView

- (instancetype) init{
    if(!(self = [super initWithFrame:CGRectMake(0, 0, 100, 100)])) return nil;
    _messageRect = CGRectInset(self.bounds, 10, 10);
    self.backgroundColor = [UIColor clearColor];
    return self;
    
}

- (void) _drawRoundRectangleInRect:(CGRect)rect withRadius:(CGFloat)radius{
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    
    CGRect rrect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height );
    
    CGFloat minx = CGRectGetMinX(rrect), midx = CGRectGetMidX(rrect), maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect), midy = CGRectGetMidY(rrect), maxy = CGRectGetMaxY(rrect);
    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFill);
}
- (void) drawRect:(CGRect)rect{
    [[UIColor colorWithWhite:0 alpha:0.8] set];
    [self _drawRoundRectangleInRect:rect withRadius:10];
    [[UIColor whiteColor] set];
    
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
                                [UIFont boldSystemFontOfSize:14], NSFontAttributeName,
                                [UIColor whiteColor], NSForegroundColorAttributeName,
                                paragraphStyle, NSParagraphStyleAttributeName,
                                nil];
    
    [_messageText drawInRect:_messageRect withAttributes:attributes];

    
    CGRect r = CGRectZero;
    r.origin.y = 15;
    r.origin.x = (NSInteger)((rect.size.width-_image.size.width)/2);
    r.size = _image.size;
    
    [_image drawInRect:r];
}

#pragma mark Setter Methods
- (void) adjust{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    
    NSDictionary *attributes = [[NSDictionary alloc] initWithObjectsAndKeys:
                                [UIFont boldSystemFontOfSize:14], NSFontAttributeName,
                                [UIColor whiteColor], NSForegroundColorAttributeName,
                                paragraphStyle, NSParagraphStyleAttributeName,
                                nil];
    
    NSStringDrawingOptions options =  NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
    CGRect rect = [_messageText boundingRectWithSize:CGSizeMake(160, 200) options:options attributes:attributes context:nil];
    
    float imageAdjustment = 0;
    if (_image) {
        imageAdjustment = 7+_image.size.height;
    }
    
    self.bounds = CGRectMake(0, 0, rect.size.width+40, rect.size.height+15+15+imageAdjustment);
    
    _messageRect.size = rect.size;
    _messageRect.size.height += 5;
    _messageRect.origin.x = 20;
    _messageRect.origin.y = 15+imageAdjustment;
    
    [self setNeedsLayout];
    [self setNeedsDisplay];
    
}
- (void) setMessageText:(NSString*)str{
    _messageText = str;
    [self adjust];
}
- (void) setImage:(UIImage*)img{
    _image = img;
    [self adjust];
}

@end


#pragma mark - TXToastCenter

@implementation TXToastCenter

#pragma mark Init & Friends
+ (TXToastCenter*) defaultCenter {
    __strong static TXToastCenter *defaultCenter = nil;
    if (!defaultCenter) {
        defaultCenter = [[TXToastCenter alloc] init];
    }
    return defaultCenter;
}
- (instancetype) init{
    if(!(self=[super init])) return nil;
    
    _alerts = [[NSMutableArray alloc] init];
    _alertView = [[TXToastView alloc] init];
    _active = NO;
    
    
    _alertFrame = CGRectMake(0, TX_SCREEN_HEIGHT-ALERT_VIEW_HEIGHT, TX_SCREEN_WIDTH, ALERT_VIEW_HEIGHT);//[UIScreen mainScreen].applicationFrame;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillAppear:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardDidHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIApplicationWillChangeStatusBarOrientationNotification object:nil];
    
    return self;
}
- (void) dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark Show Alert Message
- (void) showAlerts{
    
    if([_alerts count] < 1) {
        _active = NO;
        return;
    }
    
    _active = YES;
    _alertView.transform = CGAffineTransformIdentity;
    _alertView.alpha = 0;
    [[UIApplication sharedApplication].keyWindow addSubview:_alertView];
    
    
    
    NSArray *ar = _alerts[0];
    
    UIImage *img = nil;
    if([ar count] > 1) img = _alerts[0][1];
    
    [_alertView setImage:img];
    
    if([ar count] > 0) [_alertView setMessageText:_alerts[0][0]];
    
    
    
    _alertView.center = CGPointMake(CGRectGetMidX(_alertFrame),CGRectGetMidY(_alertFrame));
    
    
    CGRect rr = _alertView.frame;
    rr.origin.x = (int)rr.origin.x;
    rr.origin.y = (int)rr.origin.y;
    _alertView.frame = rr;
    
    UIInterfaceOrientation o = [UIApplication sharedApplication].statusBarOrientation;
    CGFloat degrees = 0;
    if(o == UIInterfaceOrientationLandscapeLeft ) degrees = -90;
    else if(o == UIInterfaceOrientationLandscapeRight ) degrees = 90;
    else if(o == UIInterfaceOrientationPortraitUpsideDown) degrees = 180;
    _alertView.transform = CGAffineTransformMakeRotation(degrees * M_PI / 180);
    _alertView.transform = CGAffineTransformScale(_alertView.transform, 2, 2);
    
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.15];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationStep2)];
    _alertView.transform = CGAffineTransformMakeRotation(degrees * M_PI / 180);
    _alertView.frame = CGRectIntegral(_alertView.frame);
    _alertView.alpha = 1;
    [UIView commitAnimations];
    
    
}
- (void) animationStep2{
    [UIView beginAnimations:nil context:nil];
    
    // depending on how many words are in the text
    // change the animation duration accordingly
    // avg person reads 200 words per minute
    NSArray * words = [_alerts[0][0] componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    double duration = MAX(((double)[words count]*60.0/200.0),1.4f);
    
    [UIView setAnimationDelay:duration];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationStep3)];
    
    UIInterfaceOrientation o = [UIApplication sharedApplication].statusBarOrientation;
    CGFloat degrees = 0;
    if(o == UIInterfaceOrientationLandscapeLeft ) degrees = -90;
    else if(o == UIInterfaceOrientationLandscapeRight ) degrees = 90;
    else if(o == UIInterfaceOrientationPortraitUpsideDown) degrees = 180;
    _alertView.transform = CGAffineTransformMakeRotation(degrees * M_PI / 180);
    _alertView.transform = CGAffineTransformScale(_alertView.transform, 0.5, 0.5);
    
    _alertView.alpha = 0;
    [UIView commitAnimations];
}
- (void) animationStep3{
    
    [_alertView removeFromSuperview];
    [_alerts removeObjectAtIndex:0];
    [self showAlerts];
    
}
- (void) postAlertWithMessage:(NSString*)message image:(UIImage*)image{
    if(message && image)
        [_alerts addObject:@[message,image]];
    else if(message)
        [_alerts addObject:@[message]];
    else if(image)
        [_alerts addObject:@[image]];
    if(!_active) [self showAlerts];
}
- (void) postAlertWithMessage:(NSString*)message{
    [self postAlertWithMessage:message image:nil];
}


#pragma mark System Observation Changes
CGRect subtractRect(CGRect wf,CGRect kf);
CGRect subtractRect(CGRect wf,CGRect kf) {
    
    
    
    if(!CGPointEqualToPoint(CGPointZero,kf.origin)){
        
        if(kf.origin.x>0) kf.size.width = kf.origin.x;
        if(kf.origin.y>0) kf.size.height = kf.origin.y;
        kf.origin = CGPointZero;
        
    }else{
        
        
        kf.origin.x = fabs(kf.size.width - wf.size.width);
        kf.origin.y = fabs(kf.size.height -  wf.size.height);
        
        
        if(kf.origin.x > 0){
            CGFloat temp = kf.origin.x;
            kf.origin.x = kf.size.width;
            kf.size.width = temp;
        }else if(kf.origin.y > 0){
            CGFloat temp = kf.origin.y;
            kf.origin.y = kf.size.height;
            kf.size.height = temp;
        }
        
    }
    return CGRectIntersection(wf, kf);
    
}
- (void) keyboardWillAppear:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect kf = [aValue CGRectValue];
    CGRect wf = [UIScreen mainScreen].bounds;
    
    [UIView beginAnimations:nil context:nil];
    _alertFrame = subtractRect(wf,kf);
    _alertView.center = CGPointMake(CGRectGetMidX(_alertFrame), CGRectGetMidY(_alertFrame));
    [UIView commitAnimations];
    
}
- (void) keyboardWillDisappear:(NSNotification *) notification {
    _alertFrame = CGRectMake(0, TX_SCREEN_HEIGHT-ALERT_VIEW_HEIGHT, TX_SCREEN_WIDTH, ALERT_VIEW_HEIGHT);//[UIScreen mainScreen].applicationFrame;
    
}
- (void) orientationWillChange:(NSNotification *) notification {
    
    NSDictionary *userInfo = [notification userInfo];
    NSNumber *v = userInfo[UIApplicationStatusBarOrientationUserInfoKey];
    UIInterfaceOrientation o = [v intValue];
    
    
    
    
    CGFloat degrees = 0;
    if(o == UIInterfaceOrientationLandscapeLeft ) degrees = -90;
    else if(o == UIInterfaceOrientationLandscapeRight ) degrees = 90;
    else if(o == UIInterfaceOrientationPortraitUpsideDown) degrees = 180;
    
    [UIView beginAnimations:nil context:nil];
    _alertView.transform = CGAffineTransformMakeRotation(degrees * M_PI / 180);
    _alertView.frame = CGRectMake((int)CGRectGetMinX(_alertView.frame), (int)CGRectGetMinY(_alertView.frame), (int)CGRectGetWidth(_alertView.frame), (int)CGRectGetHeight(_alertView.frame));
    [UIView commitAnimations];
    
}

@end
